import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login'
import Register from '@/views/Register'
import Layout from '@/views/Layout'
import ShouYe from '@/views/ShouYe'
import ZhaoFang from '@/views/ZhaoFang'
import ZiXun from '@/views/ZiXun'
import WoDe from '@/views/WoDe'
import Collect from '@/views/Collect'
import { getToken } from '@/utils/storage'

Vue.use(VueRouter)

// const routes = [
// ]

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    { path: '/register', component: Register },
    { path: '/collect', component: Collect },
    {
      path: '/',
      component: Layout,
      children: [
        { path: '/shouye', component: ShouYe },
        { path: '/zhaofang', component: ZhaoFang },
        { path: '/zixun', component: ZiXun },
        { path: '/wode', component: WoDe }
      ]
    }
  ]
})
// 全局前置守卫
// 白名单
const whiteList = ['/login', '/register']
router.beforeEach((to, from, next) => {
  // to 去哪里，from 从哪来，next是一个函数
  // 调用next才会正常 运行，next(path)拦截到指定路径
  const token = getToken
  // console.log(to.path)
  if (token) { // 如果token存在
    next()
  } else { // 去的路径是否在白名单
    if (whiteList.includes(to.path)) { // 如果是就放行
      next()
    } else { // 不是就跳转到登录
      next('/login')
    }
  }
})
export default router
